<template>
    <div>
        <card shadow="hover">
        <div class="p20">
            <div style="width: 100%;margin-left: 10px;">
                <el-form :model="form">
                    <el-row :gutter="10">
                        <el-col :span="4">
                            <el-form-item label="手机前缀:">
                                <el-input v-model="searchForm.mobileprefi" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="地区编码:">
                                <el-input v-model="searchForm.areaCode" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="省级编码:">
                                <el-input v-model="searchForm.province" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" @click="getRecords"><el-icon>
                                    <Search />
                                </el-icon>查询</el-button>
                            <el-button type="info" @click="clearData"><el-icon>
                                    <Close />
                                </el-icon>清空</el-button>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <el-button type="success" @click="addTableData" v-if="permissionStore.isPermissionsBtn('011007001')"> <el-icon>
                                    <Plus />
                                </el-icon>添加</el-button>
                            <!-- <el-button type="primary"><el-icon>
                                <Aim />
                            </el-icon>锁定</el-button> -->
                            <el-button type="primary" @click="importDialogVisible = true" v-if="permissionStore.isPermissionsBtn('011007002')"> <el-icon>
                                    <CopyDocument />
                                </el-icon>导入</el-button>
                            <!-- <el-button type="primary" @click="addTableData"><el-icon>
                                <DocumentRemove />
                            </el-icon>导出</el-button> -->
                            <el-button type="danger" @click="removeTableData" v-if="permissionStore.isPermissionsBtn('011007003')"><el-icon>
                                    <Delete />
                                </el-icon>批量删除</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="mt10">
                <el-table :data="tableData" style="width: 100%;height:60vh" stripe
                    @selection-change="handleSelectionChange" :row-style="{ height: '8px' }">
                    <el-table-column type="selection" width="85" />
                    <el-table-column type="index" width="80" label="序号" align="center" />
                    <el-table-column prop="mobileprefi" label="手机前缀" align="center" />
                    <el-table-column prop="areaCode" label="地区编码" align="center" />
                    <el-table-column prop="provinceCo" label="省级编码" align="center" />
                    <el-table-column prop="city" label="城市" align="center" />
                    <el-table-column prop="province" label="省" align="center" />
                    <el-table-column prop="operator" label="运营商" align="center" />
                    <el-table-column label="操作" align="center" v-if="permissionStore.isPermissionsBtn(['011007004','011007005'])">
                        <template #default="scope">
                            <el-button type="warning" @click="editForm(scope.$index, scope.row)" v-if="permissionStore.isPermissionsBtn('011007004')"
                                size="default">编辑</el-button>
                            <el-button type="danger" @click="deleteForm(scope.$index, scope.row)" v-if="permissionStore.isPermissionsBtn('011007005 ')"
                                size="default">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div style="margin-top: 20px;">
                <el-pagination style="justify-content: center;" v-model:current-page="currentPageIndex"
                    v-model:page-size="pageSize" :page-sizes="[10, 50]" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @current-change="handleCurrentChange" @size-change="handleSizeChange" />
            </div>
        </div>

        <div>
            <el-dialog v-model="centerDialogVisible" :title="dialogTitle" width="30%" center>
                <div>
                    <el-form :model="form" label-width="120px" label-position="top">
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="手机前缀:">
                                    <el-input v-model="submitForm.mobileprefi" placeholder="请输入手机前缀" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="地区编码:">
                                    <el-input v-model="submitForm.areaCode" placeholder="请输入地区编码" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="省份编码:">
                                    <el-input v-model="submitForm.provinceCo" placeholder="请输入省份编码" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="城市:">
                                    <el-input v-model="submitForm.city" placeholder="请输入城市" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="省份:">
                                    <el-input v-model="submitForm.province" placeholder="请输入省份" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="运营商:">
                                    <el-input v-model="submitForm.operator" placeholder="请输入运营商" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="centerDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="mySubmit">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="importDialogVisible" width="30%" center>
                <div>
                    <el-upload class="upload-demo" drag multiple :auto-upload="false" :limit="1"
                        v-model:file-list="fileList">
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text" style="height: 120px;">
                            拖拽 或 <em>点击上传</em>
                        </div>
                    </el-upload>
                    <el-button type="primary" size="default" @click="downloadTemp">下载模板</el-button>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="importDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="uploadExcel()">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        </card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectPage, insert, batchDelete, dowloadTemplate, uploadTemplate } from "@/api/bussiness/homeplace";
import {
    Delete, DocumentRemove, CopyDocument, Plus, Aim, Search, Close
} from '@element-plus/icons-vue'
import { usePermissionStore } from '@/store/modules/permission'
const permissionStore = usePermissionStore()
onMounted(() => {
    getRecords()
})

const fileList = ref([])

const submitForm = reactive({
    eid: '',
    areaCode: '',
    city: '',
    province: '',
    provinceCo: '',
    mobileprefi: '',
    operator: '',

})
const searchForm = reactive({
    areaCode: '',
    city: '',
    province: '',
    mobileprefi: '',
})
const pageSize = ref(10)

const ids = ref([])
const dialogTitle = ref('')
const total = ref()
const currentPageIndex = ref(1)
const tableData = ref<any>([])
const importDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const multipleSelection = ref<any>([])

const uploadExcel = () => {
    const formData = new FormData();
    formData.append('file', fileList.value[0].raw)
    uploadTemplate(formData).then(res => {
        if (res.code === 200) {
            importDialogVisible.value = false
            fileList.value = []
            ElMessage({
                message: '添加' + res.data + '条数据',
                type: 'success',
            })
        } else {
            ElMessage({
                message: res.message,
                type: 'warning',
            })
        }
    })
}

const downloadTemp = () => {
    dowloadTemplate().then((res) => {
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' }); // 将服务端返回的文件流（二进制）excel文件转化为blob
        // let fileName = window.decodeURI(headers['content-disposition'].split('=')[1], 'UTF-8');
        let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob);
        let downFile = document.createElement('a');
        downFile.style.display = 'none';
        downFile.href = objectUrl;
        downFile.download = '归属地模板.xlsx'; // 下载后文件名
        document.body.appendChild(downFile);
        downFile.click();
        document.body.removeChild(downFile); // 下载完成移除元素
        // window.location.href = objectUrl
        window.URL.revokeObjectURL(objectUrl); // 只要映射存在，Blob就不能进行垃圾回收，因此一旦不再需要引用，就必须小心撤销URL，释放掉blob对象。
    });
}
const getRecords = () => {
    const params = {
        pageNum: currentPageIndex.value,
        pageSize: pageSize.value,
        mobileprefi: searchForm.mobileprefi.substring(0, 7),
        areaCode: searchForm.areaCode,
        provinceCo: searchForm.province
    }
    selectPage(params).then(res => {
        if (res.code === 200) {
            tableData.value = []
            total.value = res.data.total
            tableData.value.push(...res.data.records)
        } else {
            ElMessage({
                message: res.message,
                type: 'warning',
            })
        }
    })
}
const editForm = (index: number, row: any) => {
    dialogTitle.value = '修改表单'
    centerDialogVisible.value = true
    Object.assign(submitForm, row);
}
const clearData = () => {
    searchForm.mobileprefi = ''
    searchForm.province = ''
    searchForm.areaCode = ''
}
const handleSizeChange = (val: number) => {
    currentPageIndex.value = val
    getRecords()
}
const deleteForm = (index: number, row: any) => {
    ids.value = []
    ElMessageBox.confirm(
        '是否删除本条数据',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            ids.value.push(row.eid)
            batchDeleteAll()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
const batchDeleteAll = () => {
    const params = {
        deleteIds: ids.value
    }
    batchDelete(params).then(res => {
        if (res.code === 200) {
            getRecords()
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        } else {
            ElMessage({
                message: res.message,
                type: 'warning',
            })
        }
    })
}
const mySubmit = () => {
    centerDialogVisible.value = false
    const params = {
        eid: submitForm.eid,
        areaCode: submitForm.areaCode,
        provinceCo: submitForm.provinceCo,
        operator: submitForm.operator,
        city: submitForm.city,
        province: submitForm.province,
        mobileprefi: submitForm.mobileprefi

    }
    insert(params).then(res => {
        if (res.code === 200) {
            getRecords()
            ElMessage({
                message: '操作成功',
                type: 'success',
            })
        } else {
            ElMessage({
                message: res.message,
                type: 'warning',
            })
        }
    })
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    currentPageIndex.value = val
    getRecords()
}
const handleSelectionChange = (val: any) => {
    ids.value = []
    multipleSelection.value = val
    multipleSelection.value.forEach(item => {
        ids.value.push(item.eid)
    })
}
const addTableData = () => {
    clearObj()
    dialogTitle.value = '新增表单'
    centerDialogVisible.value = true
}
const clearObj = () => {
    submitForm.eid = '',
        submitForm.areaCode = '',
        submitForm.city = '',
        submitForm.province = '',
        submitForm.mobileprefi = '',
        submitForm.provinceCo = '',
        submitForm.operator = ''
}
const removeTableData = () => {
    if (multipleSelection.value.length > 0) {
        ElMessageBox.confirm(
            '是否删除' + multipleSelection.value.length + '条数据',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                batchDeleteAll()
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
    } else {
        ElMessage({
            type: 'warning',
            message: '请选择数据',
        })
    }

}

</script>

<style scoped>
.gateInput {
    width: 50px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>